package cn.enzo.utils.db;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

/**
 * @Description 自定义转换器,将AS400的1/0转换为Boolean的TRUE/FALSE
 * @author 李yi辉
 * @date 2016年4月20日
 */
@MappedJdbcTypes(JdbcType.CHAR)
@MappedTypes({java.lang.Boolean.class})
public class BooleanTypeHandler implements TypeHandler<Boolean> {

	@Override
	public void setParameter(PreparedStatement ps, int i, Boolean parameter,
			JdbcType jdbcType) throws SQLException {
		ps.setString(i, convertBooleanTo01(parameter));
	}

	@Override
	public Boolean getResult(ResultSet rs, String columnName)
			throws SQLException {
		return convert01ToBoolean(rs.getString(columnName));
	}

	@Override
	public Boolean getResult(ResultSet rs, int columnIndex) throws SQLException {
		return convert01ToBoolean(rs.getString(columnIndex));
	}

	@Override
	public Boolean getResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		return convert01ToBoolean(cs.getString(columnIndex));
	}
	
	/**
	 * 
	 * @Description 将true/false转换为1/0
	 * @param parameter
	 * @return String
	 */
	private String convertBooleanTo01(Boolean parameter){
		String as400_01 = "0";
		if(parameter != null){
			if(parameter == true){
				as400_01 = "1";
			}
		}
		return as400_01;
	}

	/**
	 * 
	 * @Description 将1/0转换为true/false
	 * @param rsValue
	 * @return Boolean  
	 */
	private Boolean convert01ToBoolean(String rsValue){
		Boolean value = false;
		if("1".equals(rsValue)){
			value = true;
		}
		return value;
	}
}
